#!/usr/bin/python3
# -*- encoding=utf-8 -*-
import math
import requests
import json,time
import user
import resource
#import urlparse
import monitor
import base64

if __name__ == '__main__':
    
    userName = "optadmin"
    password = "Gridview@123"
    headers = {'Gridview-Token': 'OzSBLmLbGPXR0kWccMmFLA==',}
    session = requests.session()
    #登录
    user = user.User(headers,session)
    result = user.login(userName,password)
    #print result
    
    #查询资源
    #print "resource"
    resource = resource.Resource(headers,session)
    
    resourceName = 'a01r1n19'
    resId = resource.listResourceIdByName(resourceName)
    #print resId

    resourceId = resId
    res = resource.getResourceById(resourceId)
    #print res.text  

    res1 = res.json()
    sn = res1['resultData']['paramsMap']['SerialNumber']
    ip  =   res1['resultData']['paramsMap']['ManageIP']
    #print sn
    #print ip
    name = resourceName
    ident = resId
    cate = res1['resultData']['category']
    #print cate
    digest = json.dumps(res1['resultData']['paramsMap'])
    #print digest

    #print "88888888888888888888888888888888888888888"
    #查询资源的监控指标
    monitor1 = monitor.Monitor(headers,session)
    res1 = monitor1.getMetricById(resourceId)
    #print res1.text

 
    res = res1.json()

    cpu = len(res['resultData']['CPU'])
    #print cpu

    sum_memory = 0.0
    memory =  res['resultData']['MEMORY']
    for i in range(len(memory)):
        #print memory[i]["metric"][2]["value"]
        str_num = memory[i]["metric"][2]["value"]
        before_e = float(str_num.split('E')[0])
        after_e = int(str_num.split('E')[1])
        byte_num = before_e * math.pow(10, after_e)
        gb_num = byte_num / 1073741824.0

        #print gb_num
        sum_memory = sum_memory +  gb_num 

    sum_memory = str(sum_memory) + "G"
    
    sum_disk = 0.0
    disk =  res['resultData']['DISK']
    for i in range(len(disk)):
        #print disk[i]["metric"][0]["value"]
        byte_num = disk[i]["metric"][0]["value"]
        disk_num = int(byte_num) / 1073741824.0
        #print disk_num
        sum_disk = sum_disk +  disk_num
    sum_disk = sum_disk / 1024.0
    sum_disk = str(round(sum_disk,2)) + "T"
   
    #print sum_disk
    
    field = {}
    field["cpu"] = str(cpu)
    field["disk"] = sum_disk
    field["mem"] = sum_memory
    #发送数据
    dict2 = {}
    dict2["sn"] = str(sn)
    dict2["ip"] = str(ip)
    dict2["ident"] = str(ident)
    dict2["name"] = name
    dict2["cate"] = str(cate)
    dict2["uniqkey"] = "ip"
    dict2["fields"] = field
    dict2["digest"] = (base64.b64encode(json.dumps(digest).encode("utf-8"))).decode("utf-8")
    #dict2["digest"] = "fasdfas"
    data = dict2
    print(data)
    headers1 = {'X-Srv-Token': '527508138b16557952d4aeb117090716',}
    url = 'http://172.1.0.165:8002/v1/ams-ce/hosts/register'
    req = requests.post(url,data=json.dumps(data),headers=headers1)
    print(req)
    print(req.text)
    
    
